<template>
  <el-dialog v-model="visible" title="新增用户" width="50%" style="padding-right:50px;">
    <el-form label-width="100px">
		
      <el-form-item label="部门">
        <el-select v-model="data.depId">
          <el-option label="全部" value="" />
          <el-option v-for="item in depList" :key="item.did" :label="item.dname" :value="item.did" />
        </el-select>
      </el-form-item>

      <el-form-item label="打卡时间">
        <el-time-picker
          v-model="data.clockTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="选择时间"
        />
      </el-form-item>

      <el-form-item label="签退时间">
        <el-time-picker
          v-model="data.clockOutTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="选择时间"
        />
      </el-form-item>

      <el-form-item label="位置坐标">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入地点名称"
                ref="searchInput"
                @keyup.enter="handleSearch"
              />
              <div id="mapContainer" style="height: 300px; width: 100%; margin-top: 10px;"></div>
            </el-form-item>

      <el-form-item label="考勤范围">
        <el-input v-model="data.clockRange" placeholder="请输入考勤范围（米）">
          <template #append>米</template>
        </el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" @click="signAdd">确定</el-button>
      <el-button @click="visible = false">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
	import { ref, reactive, onMounted, watch, nextTick } from 'vue'
	import req from '@/request'
	import { ElMessage } from 'element-plus'
	
	const depList = ref([]);
	
	const emit = defineEmits(['upd-ok']);
	
	const visible = ref(false);
	
	
	// -------------
	const searchKeyword = ref('')
	const searchInput = ref(null)
	
	let map = null
	let marker = null
	let placeSearch = null
	let autoComplete = null
	//---------------------
	
	const open = async (_depList, row) => {
		
		for(let prop in data){
			data[prop] = row[prop];
		}
		searchKeyword.value = row.location;
		visible.value = true
		depList.value = _depList
		await nextTick()
		if (!window.AMap) {
		loadAMapScript()
		} else {
		initMap()
		}
	}
	
	const data = reactive({
	  id:'',
	  depId: '',
	  clockTime: '',
	  clockOutTime: '',
	  latitude: '',
	  longitude: '',
	  clockRange: ''
	});
	
	const signAdd = async () => {
	  try {
	    console.log("提交数据：", data)
	    await req.post('/clock/update', data)
	    emit('upd-ok')
	    visible.value = false
	    ElMessage.success('修改成功！')  // 建议修改为考勤相关描述
	  } catch (error) {
	    console.error('修改失败:', error)
	    ElMessage.error(`操作失败: ${error.response?.data?.message || error.message}`)
	  }
	}
		
	//-----------------------------------------
	const initMap = async () => {
	  await nextTick()
	  if (!window.AMap) {
	    ElMessage.error('地图加载失败，请稍后重试')
	    return
	  }
	
	  // 初始化地图
	  map = new AMap.Map('mapContainer', {
	    zoom: 13,
	    center: [116.397428, 39.90923] // 默认北京中心点
	  })
	
	  // 初始化地点搜索
	  placeSearch = new AMap.PlaceSearch({
	    map: map,
	    pageSize: 5
	  })
	
	  // 初始化输入提示
	  const inputEl = searchInput.value.$el.querySelector('input')
	  autoComplete = new AMap.AutoComplete({
	    input: inputEl
	  })
	
	  // 输入提示选择事件
	  autoComplete.on('select', (e) => {
	    if (e.poi && e.poi.location) {
	      updateMapPosition(e.poi.location)
	    }
	  })
	
	  // 地图点击事件
	  map.on('click', (e) => {
	    updateMapPosition(e.lnglat)
	  })
	}
	
	const updateMapPosition = (lnglat) => {
	  map.setCenter(lnglat)
	  data.latitude = lnglat.lat
	  data.longitude = lnglat.lng
	  updateMarker(lnglat)
	}
	
	const updateMarker = (lnglat) => {
	  if (marker) {
	    marker.setMap(null)
	  }
	  marker = new AMap.Marker({
	    position: lnglat,
	    map: map
	  })
	}
	
	const handleSearch = () => {
	  if (!searchKeyword.value.trim()) return
	  
	  placeSearch.search(searchKeyword.value, (status, result) => {
	    if (status === 'complete' && result.poiList.pois.length) {
	      const poi = result.poiList.pois[0]
	      updateMapPosition(poi.location)
	    }
	  })
	}
	
	const loadAMapScript = () => {
	  const key = 'b2d60dd176d73d5b1258115b7e62c3ec'
	  const securityJsCode = '3561748842d8404b2f3c191e049b3ddc'
	  
	  window._AMapSecurityConfig = {
	    securityJsCode: securityJsCode
	  }
	
	  const script = document.createElement('script')
	  script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}&plugin=AMap.PlaceSearch,AMap.AutoComplete`
	  script.onload = initMap
	  document.head.appendChild(script)
	}
	
	watch(visible, (val) => {
	  if (!val && map) {
	    map.destroy()
	    map = null
	    marker = null
	    autoComplete = null
	    placeSearch = null
	  }
	})
	
	defineExpose({
	    open
	});
</script>

<style>
</style>